package com.liwei.easyweibo.activity;

import com.liwei.easyweibo.R;
import com.liwei.easyweibo.util.Constant;
import com.liwei.easyweibo.util.Util;
import com.sina.net.AccessToken;
import com.sina.net.DialogError;
import com.sina.net.Weibo;
import com.sina.net.WeiboDialogListener;
import com.sina.net.WeiboException;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.weibo.api.UserAPI;
import com.tencent.weibo.constants.OAuthConstants;
import com.tencent.weibo.oauthv2.OAuthV2;
import com.tencent.weibo.webview.OAuthV2AuthorizeWebView;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
 * 绑定微博、微信
 * */
public class BindWeiboActivity extends Activity implements OnClickListener{
	private final static String TAG = "BindWeiboActivity";
	
	private RelativeLayout mSina,mTencent;
	private Weibo mWeibo;
	private TextView mTextSina,mTextTencent;
    
    //新浪微博相关
    private OAuthV2 mOauthV2;
    
    private IWXAPI mWechatApi;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		initView();
	}
	
	/**
	 * 初始化界面
	 * */
	private void initView(){
		setContentView(R.layout.bindweibo);
		
		//新浪微博绑定
		mSina = (RelativeLayout) findViewById(R.id.sina);
		mSina.setOnClickListener(this);
		
		//腾讯微博绑定
		mTencent = (RelativeLayout) findViewById(R.id.tencent);
		mTencent.setOnClickListener(this);
		
		//应用不再支持微信
//		mWechat = (RelativeLayout) findViewById(R.id.wechat);
//		mWechat.setOnClickListener(this);
		
		mTextSina 		= (TextView) findViewById(R.id.tv_state_sina);
		mTextTencent = (TextView) findViewById(R.id.tv_state_tencent);
		
		//应用不支持微信
//		mTextWechat = (TextView) findViewById(R.id.tv_state_wechat);
		boolean isSinaOauth = Util.isBindToSina(this);
		if(isSinaOauth){
			mTextSina.setText(R.string.bind_aleardy);
		}
		
		OAuthV2 oauth = Util.readTencentFromPreference(this);
		if(oauth != null){
			mTextTencent.setText(R.string.bind_aleardy);
		}
		
//		boolean isTrue = Util.readBFromPreference(this, Constant.SHAREDPRE_WECHAT);
//		if(isTrue){
//			mTextWechat.setText(R.string.bind_aleardy);
//		}
	}
	
	/**
	 * 绑定到新浪微博
	 * */
	private void bindToSina(){
		Util.d(TAG, "bindToSina.....");
		mWeibo = Weibo.getInstance();
		mWeibo.setupConsumerConfig(Constant.SINA_APP_KEY, Constant.SINA_APP_SECRET);
		
		// Oauth2.0
		// 隐式授权认证方式
		mWeibo.setRedirectUrl(Constant.SINA_URL_ACTIVITY_CALLBACK);
		mWeibo.authorize(BindWeiboActivity.this, new AuthDialogListener(BindWeiboActivity.this));
		
	}
	
	class AuthDialogListener implements WeiboDialogListener{
		private Context mContext ; 
		public AuthDialogListener(Context context){
			mContext = context;
		}
		@Override
		public void onComplete(Bundle values) {
			// TODO Auto-generated method stub
			String token = values.getString("access_token");
			String expires_in = values.getString("expires_in");
			Util.d(TAG, "expires_in is: "+expires_in);
			AccessToken accessToken = new AccessToken(token, Constant.SINA_APP_SECRET);
			accessToken.setExpiresIn(expires_in);
			Util.keepSinaAccessToken(mContext, accessToken);
			
			mTextSina.setText(R.string.bind_aleardy);
		}

		@Override
		public void onWeiboException(WeiboException e) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onError(DialogError e) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onCancel() {
			// TODO Auto-generated method stub
			
		}

	
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
        
        //腾讯微博的判断
        if(requestCode == Constant.REUSLT_CODE){
        	if(resultCode == OAuthV2AuthorizeWebView.RESULT_CODE){
        		mTextTencent.setText(R.string.bind_aleardy);
        		mOauthV2 = (OAuthV2) data.getExtras().getSerializable("oauth");
        		Util.keepTencentAccessToken(this, mOauthV2);
        		UserAPI userApi = new UserAPI(OAuthConstants.OAUTH_VERSION_2_A);
        		try {
					String resource = userApi.info(mOauthV2, "json");
					Util.d(TAG, "resource="+ resource);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} //获取用户信息
        	}
        }
	}
	
	private void bindToTencent(){
		mOauthV2 = new OAuthV2(Constant.REDIRECT_URL_TENCENT);
		mOauthV2.setClientId(Constant.CONSUMER_KEY_TENCENT);
		mOauthV2.setClientSecret(Constant.CONSUMER_SECRET_TENCENT);
		
		Intent i = new Intent(this,OAuthV2AuthorizeWebView.class);
		i.putExtra("oauth", mOauthV2);
		startActivityForResult(i,Constant.REUSLT_CODE);
	}
	
	public void bindToWechat(){
		//通过WXAPIFactory工厂，获取IWXAPI实例
		mWechatApi = WXAPIFactory.createWXAPI(this, Constant.WECHAT_APPID, false);
		
		//先判断是否安装了微信app
		boolean isAppInstalled = mWechatApi.isWXAppInstalled();
		if( !isAppInstalled ){
			Util.showToast(this, "亲，你手机上还没有安装微信哦。应用无法支持分享到好友圈");
		}
		
		//绑定之前先检查是否支持分享到好友圈
		boolean isSupported = mWechatApi.isWXAppSupportAPI();
		if(!isSupported){
			Util.showToast(this, "亲，不好意思，你的微信版本过低，应用无法支持分享到好友圈");
			return;
		}
		
//		//将应用的appid注册到微信
//		boolean isTrue = mWechatApi.registerApp(Constant.WECHAT_APPID);
//		Util.writeToPreference(this, Constant.SHAREDPRE_WECHAT, isTrue);
//		mTextWechat.setText(R.string.bind_aleardy);
	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.tencent:
			bindToTencent();
			break;
		case R.id.sina:
			bindToSina();
			break;
		}
	}
}
